<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
	<script src="../js/jquery.js"></script>
    <script src="../js/aliyun-sdk.min.js"></script>
    <script src="../js/vod-sdk-upload-1.0.6.min.js"></script>
</head>
<body>
    点播上传配置
    <hr />
    <table frame=void width="400px">
        <tr>
            <td>uploadAuth:</td>
            <td><input type="text" id="uploadAuth" size="20" value="eyJTZWN1cml0eVRva2VuIjoiQ0FJU3p3TjFxNkZ0NUIyeWZTaklvdmZpYy9ERzFieFE3NGVFUTE3V3JGUWVYc05JcEt2UDJ6ejJJSHBLZVhkdUFlQVhzL28wbW1oWjcvWVlsclVxRk1jZkdoMmNOcGN0dGNrSW9WbitKcGZadjh1ODRhQURpNUNqUWM1SG5Lb25uNTI4V2Y3d2FmK0FVQmJIQ1RtZDVNUVpvOWJUY1RHbFFDYW5VL21nZ29KbWFkSTZSeFN4YVNFOGF2NWRPZ3BscnIwZ1Z4N1dMdTMvQ2dQMnBXRFNBVUYwMkhwN2tuZ3R3SzY0Mk5HNTl4N0NqVVh6MFBNb3Y0RDJLNVRHSDg1M0o4VmJVc3lwK2ZGeWFxdloyVFJNMWdCTzg2NTZsODRoL2l6YzdQV2NHRVZwNmcrYUtKQXhtNzhKRmdKaVliVWdFS05wdGVYMWtlWUMydGJlaklQcTBSMUFUL2czVkMzVVg5S24yOUNXV3JIclpOYy9NT3lqWWl1VmlZcmZiTUN2NGxsN1BpcEhjVjhUY0lkNkwySXZCeFpyRTJ6d2RvWDVxSDNrTXk3NkZQRGZqL0J1aXNZb2xBaTNyWURWZndEWEcrM0JpWDVkWXNka01RWndIRGM2bUVlOFcvNURMQ1VVS0FzL1grN05GZDByS2hWRzlZR1E1RjJORFhNL25pd1A0YVNrTzZ1TDVacHlNOXV2QXNoMHRxTUdmNGxEdm1jUVNGRDZkcW1qa0U5OGRoWStHK2dManZlMWFjN2l0dVRibUxUS01iVGNkdGtEdTBSSGR3N1dveEdFUUdock1UYkw0ZGt1ZWFzMkRBSWxKMjZuR29BQmxVdHF5Y1BuLzhTTDkxb2RYT045YmJ5eXdzc1NBb1U1RjIrcUNBbGdLWkFhbzNMTlRUQ0tsM2djSGZFQlpubWJvN3lXQnEyMktMR3NnaWFmRDhhZ3JUQUlJMnY1aHBJMGFwWjJwUVc4bnV5eU9rbVYwaFBGcW8wUmlhYmJMZksrN0JLVkpyYVNEOXB5cGt3Uk52TXVnRHQ1aDAvTTZwem1qLzFacEdzS25yaz0iLCJBY2Nlc3NLZXlJZCI6IlNUUy5DNFc4SnI4Y3FYRW9BeGdIVEtSTGRLbmQ5IiwiQWNjZXNzS2V5U2VjcmV0IjoiSHpRWEhNaERIODIxRnFXVDJoZXRWRHRudDVwQlJwd2ZldWtHNTVLSHJvaVYiLCJFeHBpcmF0aW9uIjoiMjAxNy0wNC0wOFQwMzozMzo0MFoifQ=="></td>
            <td>uploadAddress:</td>
            <td><input type="text" id="uploadAddress" size="20" value="eyJFbmRwb2ludCI6Imh0dHBzOi8vb3NzLWNuLXNoYW5naGFpLmFsaXl1bmNzLmNvbSIsIkJ1Y2tldCI6ImluLTIwMTcwMzI4MjEyOTI3NzA0LTQxYzUzbXU3ZmIiLCJGaWxlTmFtZSI6IjE1QjRCNjhFRjlBMTcwMjc5MDM0NTM1NzgyNzAwMDAwMDAwLTAwMDYtMENBRC1DNUE5LTdBMDMwMDAwMDAwMC5tcDQifQ=="></td>
        </tr>
    </table>
    <hr />
    OSS上传配置
    <hr />
    <table frame=void width="400px">
        <tr>
            <td>accessKeyId:</td>
            <td><input type="text" id="accessKeyId" size="20" value="LTAIRrPto4hbOFhk"></td>
            <td>accessKeySecret:</td>
            <td><input type="text" id="accessKeySecret" size="40" value="3uMUFH5pD2We0BiH7bsPOh9m5ENKUq"></td>
        </tr>
        <tr>
            <td>secretToken:</td>
            <td><input type="text" id="secretToken" size="40" value=""></td>
            <td>expireTime:</td>
            <td><input type="text" id="expireTime" size="20" value=""></td>
        </tr>
        <tr>
            <td>endpoint:</td>
            <td><input type="text" id="endpoint" size="40" value="http://oss-cn-hangzhou.aliyuncs.com"></td>
            <td>bucket:</td>
            <td><input type="text" id="bucket" size="20" value="testbucket"></td>
        </tr>
        <tr>
            <td>object路径:</td>
            <td><input type="text" id="objectPre" size="20" value="uploadtest/"></td>
        </tr>
    </table>
    <hr />

    文件管理
    <hr />
    <input type="file" name="file" id="files" multiple/>
    <button type="button" onclick="deleteFile()">删除文件</button>
    <input type="text" id="deleteIndex" size="3" value="0">
    <button type="button" onclick="cancelFile()">取消文件</button>
    <input type="text" id="cancelIndex" size="3" value="0">

    <button type="button" onclick="resumeFile()">恢复文件</button>
    <input type="text" id="resumeIndex" size="3" value="0">

    <hr />
    列表管理
    <hr />
    <button type="button" onclick="getList()">获取上传列表</button>
    <button type="button" onclick="clearList()">清理上传列表</button>
    <hr />
    上传管理
    <hr/>
    <button type="button" onclick="start()">开始上传</button>
    <button type="button" onclick="stop()">停止上传</button>
    <button type="button" onclick="resumeWithToken()">Token恢复上传</button>
    <hr />
    <select multiple="multiple" id="textarea" style="position:relative; width:620px; height:450px; vertical-align:top; border:1px solid #cccccc;"></select>
    <button type="button" onclick="clearLog()">清日志</button>

<script>

    var uploader;
    window.onload = new function() {
        uploader = new VODUpload({
            // 文件上传失败
            'onUploadFailed': function (uploadInfo, code, message) {
                log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
            },
            // 文件上传完成
            'onUploadSucceed': function (uploadInfo) {
				console.log(uploadInfo)
                log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
            },
            // 文件上传进度
            'onUploadProgress': function (uploadInfo, totalSize, uploadedSize) {
				console.log(uploadInfo)
                log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(uploadedSize * 100 / totalSize) + "%");
            },
            // STS临时账号会过期，过期时触发函数
            'onUploadTokenExpired': function () {
                log("onUploadTokenExpired");
                if (isVodMode()) {
                    // 实现时，从新获取UploadAuth
                    // uploader.resumeUploadWithAuth(uploadAuth);
                } else if (isSTSMode()) {
                    // 实现时，从新获取STS临时账号用于恢复上传
                    // uploader.resumeUploadWithToken(accessKeyId, accessKeySecret, secretToken, expireTime);
                }
            },
            // 开始上传
            'onUploadstarted': function (uploadInfo) {
			
                if (isVodMode()) {
                  /*  var uploadAuth = document.getElementById("uploadAuth").value;
                    var uploadAddress = document.getElementById("uploadAddress").value;*/
                    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress);
                }
                log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
            }
        });

        var accessKeyId = document.getElementById("accessKeyId").value;
        var accessKeySecret = document.getElementById("accessKeySecret").value;
        var secretToken = document.getElementById("secretToken").value;
        var expireTime = document.getElementById("expireTime").value;

        if (isVodMode()) {
            // 点播上传。每次上传都是独立的鉴权，所以初始化时，不需要设置鉴权
            uploader.init();
        } else if (isSTSMode()) {
            // OSS直接上传:STS方式，安全但是较为复杂，建议生产环境下使用。
            // 临时账号过期时，在onUploadTokenExpired事件中，用resumeWithToken更新临时账号，上传会续传。
            uploader.init(accessKeyId, accessKeySecret, secretToken, expireTime);
        } else {
            // OSS直接上传:AK方式，简单但是不够安全，建议测试环境下使用。
            uploader.init(accessKeyId, accessKeySecret);
        }
    };

    document.getElementById("files")
        .addEventListener('change', function (event) {
            var endpoint = document.getElementById("endpoint").value;
            var bucket = document.getElementById("bucket").value;
            var objectPre = document.getElementById("objectPre").value;
            var userData;
            if (isVodMode()) {
                userData = '{"Vod":{"UserData":"{"IsShowWaterMark":"false","Priority":"7"}"}}';
            } else {
                userData = '{"Vod":{"Title":"this is title.我是标题","Description":"this is desc.我是描述","CateId":"19",\
                "Tags":"tag1,tag2,标签3","UserData":"user data"}}';
            }

            for(var i=0; i<event.target.files.length; i++) {
				console.log(event.target.files[i])
                log("add file: " + event.target.files[i].name);
				//得到文件名字和大小发送接口
				$.ajax({
					//url: "json/getInfo.php",
					url: "/json/api.php?url=http://172.16.6.209:8080/live/upload",
					data:{fileName:event.target.files[i].name,fileSize:event.target.files[i].size},
					type: "get",
					dataType: "json",
					success: function(data) {
						window.uploadAuth=data.uploadAuth
						window.uploadAddress=data.uploadAddress
					},
					error: function(er) {
						BackErr(er);
					}
				});
                if (isVodMode()) {
                    // 点播上传。每次上传都是独立的OSS object，所以添加文件时，不需要设置OSS的属性
                    uploader.addFile(event.target.files[i], null, null, null, userData);
                } else {
                    uploader.addFile(event.target.files[i], endpoint, bucket, objectPre + event.target.files[i].name, userData);
                }
            }
        });

    var textarea=document.getElementById("textarea");

    function start() {
        log("start upload.");
        uploader.startUpload();
    }

    function stop() {
        log("stop upload.");
        uploader.stopUpload();
    }

    function resumeWithToken() {
        log("resume upload with token.");
        var uploadAuth = document.getElementById("uploadAuth").value;

        var accessKeyId = document.getElementById("accessKeyId").value;
        var accessKeySecret = document.getElementById("accessKeySecret").value;
        var secretToken = document.getElementById("secretToken").value;
        var expireTime = document.getElementById("expireTime").value;

        if (isVodMode()) {
            uploader.resumeUploadWithAuth(uploadAuth);
        } else if (isSTSMode()) {
            uploader.resumeUploadWithToken(accessKeyId, accessKeySecret, secretToken, expireTime);
        }
    }

    function clearList() {
        log("clean upload list.");
        uploader.cleanList();
    }

    function getList() {
        log("get upload list.");
        var list = uploader.listFiles();
        for (var i=0; i<list.length; i++) {
            log("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
        }
    }

    function deleteFile() {
        if (document.getElementById("deleteIndex").value) {
            var index = document.getElementById("deleteIndex").value
            log("delete file index:" + index);
            uploader.deleteFile(index);
        }
    }

    function cancelFile() {
        if (document.getElementById("cancelIndex").value) {
            var index = document.getElementById("cancelIndex").value
            log("cancel file index:" + index);
            uploader.cancelFile(index);
        }
    }

    function resumeFile() {
        if (document.getElementById("resumeIndex").value) {
            var index = document.getElementById("resumeIndex").value
            log("resume file index:" + index);
            uploader.resumeFile(index);
        }
    }

    function clearLog() {
        textarea.options.length = 0;
    }

    function log(value) {
        if (!value) {
            return;
        }

        var len = textarea.options.length;
        if (len > 0 && textarea.options[len-1].value.substring(0, 40) == value.substring(0, 40)) {
            textarea.remove(len-1);
        } else if (len > 25) {
            textarea.remove(0);
        }

        var option=document.createElement("option");
        option.value=value,option.innerHTML=value;
        textarea.appendChild(option);
    }

    function isVodMode() {
        var uploadAuth = document.getElementById("uploadAuth").value;
        return (uploadAuth && uploadAuth.length > 0);
    }

    function isSTSMode() {
        var secretToken = document.getElementById("secretToken").value;
        var expireTime = document.getElementById("expireTime").value;
        if (!isVodMode()) {
            if (secretToken && secretToken.length > 0 && expireTime && expireTime.length > 0) {
                return true;
            }
        }
        return false;
    }
</script>

</body>
</html>
